package com.pig4cloud.pig.module.service.product.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.common.core.exception.TransactionalException;
import com.pig4cloud.pig.common.core.util.OrderUtil;
import com.pig4cloud.pig.common.core.wx.WxAppPay;
import com.pig4cloud.pig.module.api.entity.product.WarmHeartCashRecord;
import com.pig4cloud.pig.module.api.entity.wx.WxPayTransaction;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.mapper.product.WarmHeartCashRecordMapper;
import com.pig4cloud.pig.module.mapper.splitAccount.SplitAccountMapper;
import com.pig4cloud.pig.module.mapper.splitAccount.SplitAccountRecordMapper;
import com.pig4cloud.pig.module.mapper.wx.WxUserMapper;
import com.pig4cloud.pig.module.service.product.IWarmHeartCashRecordService;
import com.pig4cloud.pig.module.service.splitAccount.ISplitAccountService;
import com.pig4cloud.pig.module.service.wx.IWxPayTransactionService;
import com.pig4cloud.pig.module.service.wx.IWxTemplateService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 暖心宝上传记录，打款记录Service业务层处理
 *
 * @author ruoyi
 * @date 2022-10-28
 */
@Service
public class WarmHeartCashRecordServiceImpl extends ServiceImpl<WarmHeartCashRecordMapper, WarmHeartCashRecord> implements IWarmHeartCashRecordService {

	@Resource
	private WarmHeartCashRecordMapper warmHeartCashRecordMapper;
	@Resource
	private IWxTemplateService wxTemplateService;
	@Resource
	private IWxUserService wxUserService;
	@Resource
	private WxUserMapper wxUserMapper;
	@Resource
	private IWxPayTransactionService payTransactionService;
	@Resource
	private SplitAccountRecordMapper splitAccountRecordMapper;
	@Resource
	private SplitAccountMapper splitAccountMapper;
	@Resource
	private ISplitAccountService splitAccountService;
//	@Resource
//	private ISysConfigService sysConfigService;


	@Value("${web.appid}")
	private String appid;
	@Value("${web.secret}")
	private String secret;
	@Value("${web.mch_id}")
	private String mch_id;
	@Value("${web.api_key}")
	private String api_key;
	@Value("${web.keyPath}")
	private String keyPath;//微信支付的回调地址


	@Override
	@Transactional
	public Map<String, Object> checkRecord(WarmHeartCashRecord warmHeartCashRecord) {
		Map<String,Object> map = new HashMap<>();
		int ret = 0;
		try{
			double payMoney = 5d;
			String regBagMoney = "";// sysConfigService.selectConfigByKey("warm.heart.reg_bag");
			if(StrUtil.isNotEmpty(regBagMoney)){
				payMoney = Double.parseDouble(regBagMoney);
			}
//			WxUser wxUser = wxUserService.findById(warmHeartCashRecord.getUserId());
			//账户类型  0 - 平台   1 - 物业  2 -  小区  3 - 商家   4 - 个人
//			SplitAccount splitAccount = splitAccountService.getAccountByUserId(warmHeartCashRecord.getUserId(),4,warmHeartCashRecord.getUserId());
			map.put("result_code","FAIL");
			map.put("err_code_des","请求失败");
			int status = 0;
			if(StrUtil.isEmpty(warmHeartCashRecord.getTradeNo())){
				warmHeartCashRecord.setTradeNo(OrderUtil.getPayNo());
			}
			warmHeartCashRecord.setPayMoney(new BigDecimal(payMoney));
			WxAppPay wxAppPay = new WxAppPay("", secret, appid, mch_id,api_key);
			Map<String, String> retRequest = wxAppPay.weixinChangePay(warmHeartCashRecord.getTradeNo(),new BigDecimal(payMoney),warmHeartCashRecord.getOpenId(),keyPath,"暖心保红包奖励");
			if(retRequest.containsKey("return_code")){
				String result_code = retRequest.get("result_code");
				String err_code_des = retRequest.containsKey("err_code_des") ? retRequest.get("err_code_des") : "";
				map.put("result_code",result_code);
				map.put("err_code_des",err_code_des);
				warmHeartCashRecord.setResultCode(result_code);
				if(result_code.equals("SUCCESS")){
					warmHeartCashRecord.setPayState(1);//支付成功
					warmHeartCashRecord.setPayTime(new Date());
					map.put("err_code_des","提现成功");
					status = 1;

					WxUser user  = wxUserService.findById(warmHeartCashRecord.getUserId());

					// 添加 微信支付的 动账记录
					WxPayTransaction transaction = new WxPayTransaction();
					transaction.setPayType(0);// 0 -微信支付
					transaction.setTransactionId(warmHeartCashRecord.getTradeNo());
					transaction.setUserId(user.getId());
					transaction.setFeeType("warm_heart_red_bag");
					transaction.setTotalMoney(warmHeartCashRecord.getPayMoney());
					if(StrUtil.isNotEmpty(user.getNickName())){
						transaction.setNickName(EmojiParser.parseToAliases(user.getNickName()));
					}
					transaction.setCreateTime(new Date());
					transaction.setInOrOut(0);//动账  0 - 出账 1 - 进账
					transaction.setRemark("暖心保红包奖励");
					payTransactionService.save(transaction);
				}else{
					warmHeartCashRecord.setPayState(2);//支付失败
					warmHeartCashRecord.setErrCodeDes(err_code_des);
				}
				String pay_str = retRequest.get("pay_str");
				String reback_str = retRequest.get("reback_str");
				warmHeartCashRecord.setPayStr(pay_str);
				warmHeartCashRecord.setRebackStr(reback_str);
			}

			ret = warmHeartCashRecordMapper.updateById(warmHeartCashRecord);
			if(ret <= 0){
				throw new TransactionalException("warmHeartCashRecordMapper updateById error");
			}

//			wxTemplateService.sendWxMsgTiXian(wxUser,warmHeartCashRecord,splitAccount.getSplitMoney().doubleValue());
			map.put("ret",ret);
			return map;
		}catch (Exception e){
			e.printStackTrace();
			throw new TransactionalException("splitAccountRecordMapper insert error");
		}
	}


	/**
	 *  重新打款
	 * @param warmHeartCashRecord
	 * @return
	 */
	@Override
	@Transactional
	public int resetCash(WarmHeartCashRecord warmHeartCashRecord) {
		int ret = 0;
		try{
			//打款失败
			if (warmHeartCashRecord.getCheckState()  == 1 && warmHeartCashRecord.getPayState()  == 2) {
				String remark = "暖心保红包奖励";
				if(warmHeartCashRecord.getOpenId() == null){
					WxUser wxUser = wxUserService.findById(warmHeartCashRecord.getUserId());
					if(wxUser!=null){
						warmHeartCashRecord.setOpenId(wxUser.getOpenId());
					}
				}
				WxAppPay wxAppPay = new WxAppPay("", secret, appid, mch_id, api_key);
				Map<String, String> retRequest = wxAppPay.weixinChangePay(warmHeartCashRecord.getTradeNo(), warmHeartCashRecord.getPayMoney(), warmHeartCashRecord.getOpenId(), keyPath, remark);
				if (retRequest.containsKey("return_code")) {
					String result_code = retRequest.get("result_code");
					String err_code_des = retRequest.containsKey("err_code_des") ? retRequest.get("err_code_des") : "";
					warmHeartCashRecord.setResultCode(result_code);
					if (result_code.equals("SUCCESS")) {
						warmHeartCashRecord.setPayState(1);//支付成功
						warmHeartCashRecord.setErrCodeDes(err_code_des);

						WxUser wxUser = wxUserService.findById(warmHeartCashRecord.getUserId());
						// 添加 微信支付的 动账记录
						WxPayTransaction transaction = new WxPayTransaction();
						transaction.setPayType(0);// 0 -微信支付
						transaction.setTransactionId(warmHeartCashRecord.getTradeNo());
						transaction.setUserId(wxUser.getId());
						transaction.setFeeType("warm_heart_red_bag");
						transaction.setTotalMoney(warmHeartCashRecord.getPayMoney());
						if(StrUtil.isNotEmpty(wxUser.getNickName())){
							transaction.setNickName(EmojiParser.parseToAliases(wxUser.getNickName()));
						}
						transaction.setCreateTime(new Date());
						transaction.setInOrOut(0);//动账  0 - 出账 1 - 进账
						transaction.setRemark("暖心保红包奖励, 重新打款");
						payTransactionService.save(transaction);
					} else {
						warmHeartCashRecord.setPayState(2);//支付失败
						warmHeartCashRecord.setErrCodeDes(err_code_des);
					}
					String pay_str = retRequest.get("pay_str");
					String reback_str = retRequest.get("reback_str");
					warmHeartCashRecord.setPayStr(pay_str);
					warmHeartCashRecord.setRebackStr(reback_str);

					ret = warmHeartCashRecordMapper.updateById(warmHeartCashRecord);
					if (ret <= 0) {
						throw new TransactionalException("cashRecordMapper system error");
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
			throw new TransactionalException("addCashRecord system error");
		}
		return ret;
	}

	@Override
	public WarmHeartCashRecord selectTongji(Map<String, Object> map) {
		return warmHeartCashRecordMapper.selectTongji(map);
	}
}
